//https://leetcode.cn/problems/implement-stack-using-queues/

typedef int QDatatype;

typedef struct QueueNode
{
	struct QueueNode* next;
	QDatatype data;
}QNode;

typedef struct Queue
{
	QNode* head;
	QNode* tail;
	int size;
}Queue;

typedef struct {
	Queue q1;
	Queue q2;
} MyStack;


void QInit(Queue* pq)
{
	assert(pq);

	pq->tail = NULL;
	pq->head = NULL;
	pq->size = 0;

}

void QDestroy(Queue* pq)
{
	assert(pq);

	QNode* cur = pq->head;
	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->head = NULL;
	pq->tail = NULL;
	pq->size = 0;
}

int QSize(Queue* pq)
{
	assert(pq);

	return pq->size;
}

bool QEmpty(Queue* pq)
{
	assert(pq);

	return pq->head == NULL && pq->tail == NULL;
}

void QPush(Queue* pq, QDatatype x)
{
	assert(pq);

	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc fail\n");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;

	if (pq->head == NULL)
	{
		assert(pq->tail == NULL);
		pq->head = pq->tail = newnode;

	}

	else
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}
	pq->size++;
}

void QPop(Queue* pq)
{
	assert(pq);
	assert(!QEmpty(pq));

	QNode* cur = pq->head;
	QNode* next = cur->next;
	free(cur);
	pq->head = next;
	if (pq->head == NULL)
	{
		pq->tail = NULL;
	}

	/*if (pq->head->next == NULL)
	{
		free(pq->head);
		pq->head = pq->tail = NULL;
	}

	else
	{
		QNode* cur = pq->head;
		QNode* next = cur->next;
		free(cur);
		pq->head = next;
	}*/
	pq->size--;
}

QDatatype QBack(Queue* pq)
{
	assert(pq);
	assert(!QEmpty(pq));

	return pq->tail->data;
}

QDatatype QFront(Queue* pq)
{
	assert(pq);
	assert(!QEmpty(pq));

	return pq->head->data;
}

MyStack* myStackCreate() {

	MyStack* ptr = (MyStack*)malloc(sizeof(MyStack));
	if (ptr == NULL)
	{
		perror("malloc fail\n");
		return NULL;
	}

	QInit(&ptr->q1);
	QInit(&ptr->q2);

	return ptr;

}

void myStackPush(MyStack* obj, int x) {

	if (!QEmpty(&obj->q1))
	{
		QPush(&obj->q1, x);
	}
	else
	{
		QPush(&obj->q2, x);
	}

}

int myStackPop(MyStack* obj) {

	Queue* Qempty = &obj->q1;
	Queue* Qnonempty = &obj->q2;
	if (!QEmpty(Qempty))
	{
		Qempty = &obj->q2;
		Qnonempty = &obj->q1;
	}

	//倒数剧
	while (QSize(Qnonempty) > 1)
	{
		QPush(Qempty, QFront(Qnonempty));
		QPop(Qnonempty);
	}

	int top = QFront(Qnonempty);
	QPop(Qnonempty);

	return top;

}

int myStackTop(MyStack* obj) {

	if (!QEmpty(&obj->q1))
	{
		return QBack(&obj->q1);
	}

	else
	{
		return QBack(&obj->q2);
	}


}

bool myStackEmpty(MyStack* obj) {

	return QEmpty(&obj->q1) && QEmpty(&obj->q2);

}

void myStackFree(MyStack* obj) {

	QDestroy(&obj->q1);
	QDestroy(&obj->q2);
	free(obj);

}